package com.ilearn.rest.service;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/27 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */
import java.util.List;
import java.util.concurrent.CompletableFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class AsyncService {

    private static Logger log = LoggerFactory.getLogger(AsyncService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Async("asyncExecutor")
    public CompletableFuture<List<String>> getEmployeeName() throws InterruptedException {
        log.info("getEmployeeName starts " + Thread.currentThread().getName());

        List<String> employeeNameData = restTemplate.getForObject("http://localhost:8080/names", List.class);

        log.info("employeeNameData, {}", employeeNameData);
        Thread.sleep(1000L); // Intentional delay
        log.info("employeeNameData completed " + Thread.currentThread().getName());
        return CompletableFuture.completedFuture(employeeNameData);
    }

    @Async("asyncExecutor")
    public CompletableFuture<List<String>> getEmployeeAddress() throws InterruptedException {
        log.info("getEmployeeAddress starts " + Thread.currentThread().getName());

        List<String> employeeAddressData = restTemplate.getForObject("http://localhost:8080/addresses", List.class);

        log.info("employeeAddressData, {}", employeeAddressData);
        Thread.sleep(1000L); // Intentional delay
        log.info("employeeAddressData completed " + Thread.currentThread().getName());
        return CompletableFuture.completedFuture(employeeAddressData);
    }

    @Async("asyncExecutor")
    public CompletableFuture<List<String>> getEmployeePhone() throws InterruptedException {
        log.info("getEmployeePhone starts " + Thread.currentThread().getName());

        List<String> employeePhoneData = restTemplate.getForObject("http://localhost:8080/phones", List.class);

        log.info("employeePhoneData, {}", employeePhoneData);
        Thread.sleep(1000L); // Intentional delay
        log.info("employeePhoneData completed " + Thread.currentThread().getName());
        return CompletableFuture.completedFuture(employeePhoneData);
    }
}